layui.use(['form','layer','table','laytpl'],function(){
    var form = layui.form,
        //layer = parent.layer === undefined ? layui.layer : top.layer,
        layer = layui.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    
    //产品列表
    var tableIns = table.render({
        elem: '#productList',
        method: 'post',
        url : '../product/dataGrid',
        //url : '../static/json/pic.json',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 20,
        initSort: {
            field: 'createTime' //排序字段，对应 cols 设定的各字段名
            ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        id : "productListTable",
        cols : [[
            {field: 'name', title: '产品名称', style:'height:100px;', minWidth:50, align:"center"},
            {field: 'introduce', title: '产品介绍', style:'height:100px;', minWidth:150, align:"center"},
            {field: 'postage', title: '产品资费', style:'height:100px;', minWidth:50, align:"center"},
            {field: 'picture', title: '产品图片', width:180, align:"center",templet:function(d){
            	if (typeof(d.picture) == "undefined"){
            		return '未上传图片';
            	}else{
            		return '<img src="'+d.picture+'" height="30"  onclick=showImg("'+d.picture+'") />';
            	}
            }},
            {field: 'prescription', title: '开通时效', style:'height:100px;', minWidth:50, align:"center",templet:function(d){
                if(d.prescription == "0"){
                    return "立即开通";
                }else if(d.prescription == "1"){
                    return "下月开通";
                }else if(d.prescription == "2"){
                	return "下季度开通";
                }else{
                    return "未知类型";
                }
            }},
            {field: 'createTime', title: '创建时间', style:'height:100px;', minWidth:50, align:"center"},
            {title: '操作', style:'height:100px;', minWidth:175, templet:'#productListBar',fixed:"right",align:"center"}
        ]]
    });

    //搜索
    $(".search_btn").on("click",function(){
    	var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
        if($(".searchVal").val() != ''){
        	setTimeout(function(){
        		table.reload("productListTable",{
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                    	name: $(".searchVal").val()  //搜索的关键字
                    }
                });
    			layer.close(index);
    		},2000);
        }else{
            //layer.msg("请输入搜索的内容");
        	tableIns.reload();
        	layer.close(index);
        }
    });

    //添加产品
    function addUser(){
        var index = layui.layer.open({
            title : "添加产品",
            type : 2,
            content : "../product/addProduct",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    
    //编辑产品
    function editProduct(edit){
        var index = layer.open({
            title : "编辑产品",
            type : 2,
            content : "../product/editPage?id=" + edit.id,
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                body.find(".prescription").val(edit.prescription);  //开通时效
                body.find("#productFace").attr('src',edit.picture);//图片
                window.sessionStorage.setItem('productFace',edit.picture);
                form.render();
                setTimeout(function(){
                    layer.tips('点击此处返回产品列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layer.full(window.sessionStorage.getItem("index"));
        })
    }
    
    //分享产品
    function shareProduct(share){
        var index = layui.layer.open({
            title : "分享产品",
            type : 2,
            content : "../product/sharePage?id=" + share.id,
            area: ['540px', '520px'],
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                //body.find(".prescription").val(edit.prescription);  //开通时效
                //body.find("#productFace").attr('src',edit.picture);//图片
                //window.sessionStorage.setItem('productFace',edit.picture);
                form.render();
                setTimeout(function(){
                    layui.layer.tips('点击此处返回产品列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
    }
    
    $(".addPro_btn").click(function(){
        addUser();
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('productListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        }else{
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(productList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
        	editProduct(data);
        }else if(layEvent === 'share'){ //分享
        	shareProduct(data);
        }else if(layEvent === 'usable'){ //启用禁用
            var _this = $(this),
                usableText = "是否确定禁用此用户？",
                btnText = "已禁用";
            if(_this.text()=="已禁用"){
                usableText = "是否确定启用此用户？",
                btnText = "已启用";
            }
            layer.confirm(usableText,{
                icon: 3,
                title:'系统提示',
                cancel : function(index){
                    layer.close(index);
                }
            },function(index){
                _this.text(btnText);
                layer.close(index);
            },function(index){
                layer.close(index);
            });
        }else if(layEvent === 'del'){ //删除
        	var id = data.id;
            layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
    			$.ajax({
      			type : "POST",
      			url : "../user/delete",
      			data : {
      				"id" : id
      			},
      			success : function() {
      				top.layer.msg("用户删除成功！");
      	 			tableIns.reload();
                    layer.close(index);
      			}
    			});
            });
        }
    });
})
